<template>
  <!-- 搜索栏 -->
  <el-card class="search-card">
    <el-form :model="searchForm" label-width="80px" inline>
      <el-form-item label="工单编号">
        <el-input v-model="searchForm.productionOrderCode" placeholder="工单编号" clearable/>
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="searchForm.productionOrderName" placeholder="工单名称" clearable/>
      </el-form-item>
      <el-form-item label="单据来源">
        <el-select style="width: 200px" clearable v-model="searchForm.productionOrderSource" placeholder="单据来源">
          <el-option
              v-for="dictData in productionOrderSourceDictDataList"
              :value="dictData.id"
              :label="dictData.dictLabel"
              :key="dictData.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input v-model="searchForm.materialCode" placeholder="物料编号" clearable/>
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input v-model="searchForm.materialName" placeholder="物料名称" clearable/>
      </el-form-item>

      <el-form-item label="客户编号">
        <el-input v-model="searchForm.customerCode" placeholder="客户编号" clearable/>
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="searchForm.customerName" placeholder="客户名称" clearable/>
      </el-form-item>
      <el-form-item label="需求日期">
        <el-input v-model="searchForm.requestDate" placeholder="需求日期" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 列表 -->
  <el-card class="table-card">
    <el-table
        :data="productionOrderList"
        border
        stripe
    >
      <el-table-column prop="productionOrderCode" label="工单编号">
        <template #default="scope">
          <el-link type="primary" @click="previewProductionOrder(scope.row)">{{ scope.row.productionOrderCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderName" label="工单名称"/>
      <el-table-column prop="sourceDictData.dictLabel" label="工单来源"/>
      <el-table-column prop="orderCode" label="订单编号"/>
      <el-table-column prop="materialCode" label="产品/物料编号"/>
      <el-table-column prop="materialName" label="产品/物料名称"/>
      <el-table-column prop="productionOrderQuantity" label="工单数量"/>
      <el-table-column prop="finishQuantity" label="已生产数量"/>
      <el-table-column prop="customerCode" label="客户编号"/>
      <el-table-column prop="customerName" label="客户名称"/>
      <el-table-column prop="requestDate" label="需求日期"/>
      <el-table-column prop="statusDictData.dictLabel" label="排产状态">
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" @click="handleProSchedule(scope.row)">排产</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!--   分页栏     -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!--  弹窗-->
  <el-dialog
      :title="dialogTitle"
      v-model="scheduleDialogVisable"
      width="80%">
    <el-form v-model="productionOrderForm">
      <!-- 第一行：工单编号 + 工单名称 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工单编号">
            <el-input disabled v-model="productionOrderForm.productionOrderCode" placeholder="请输入工单编号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工单名称">
            <el-input disabled v-model="productionOrderForm.productionOrderName" placeholder="请输入工单名称"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：来源类型 + 订单编号 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="来源类型">
            <el-select disabled style="width: 120px" clearable v-model="productionOrderForm.productionOrderSource"
                       placeholder="工单类型">
              <el-option
                  v-for="dictData in productionOrderSourceDictDataList"
                  :value="dictData.id"
                  :label="dictData.dictLabel"
                  :key="dictData.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="isCustomerOrder !== false">
          <el-form-item label="订单编号">
            <el-input disabled v-model="productionOrderForm.orderCode" placeholder="请输入订单编号"/>
          </el-form-item>
        </el-col>
      </el-row>


      <!--：产品编号 + 产品名称 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品编号">
            <el-input v-model="productionOrderForm.materialCode" placeholder="请选择产品" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称">
            <el-input v-model="productionOrderForm.material.name" placeholder="请选择产品" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行：规格型号 + 单位 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规格型号">
            <el-input v-model="productionOrderForm.material.specification" placeholder="请选择产品" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位">
            <el-input v-model="productionOrderForm.material.unit.name" placeholder="请选择产品" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第六行：工单数量 + 需求日期 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工单数量">
            <el-input-number v-model="productionOrderForm.productionOrderQuantity" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="需求日期">
            <el-date-picker
                v-model="productionOrderForm.requestDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择需求日期"
                disabled
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行：客户编码 + 客户名称 -->
      <el-row :gutter="20" v-if="productionOrderForm.customer">
        <el-col :span="12">
          <el-form-item label="客户编码">
            <el-input v-model="productionOrderForm.customerCode" placeholder="请选择客户" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称">
            <el-input v-model="productionOrderForm.customer.name" placeholder="请输入客户名称" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第八行：供应商编码 + 供应商名称 -->
      <el-row :gutter="20" v-if=" productionOrderForm.supplier">
        <el-col :span="12">
          <el-form-item label="供应商编码">
            <el-input v-model="productionOrderForm.supplierCode" placeholder="请选择供应商" disabled>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商名称">
            <el-input v-model="productionOrderForm.supplier.name" placeholder="请选择供应商" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第九行：备注 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
                v-model="productionOrderForm.remark"
                type="textarea"
                placeholder="请输入内容"
                disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-card v-if="isNullWithWorkflow">
      <div>
        <h2>该产品没有匹配的工艺，请前往设计</h2>
      </div>
    </el-card>
    <el-card v-else>
      <el-tabs type="border-card" @tab-click="handleWorkflowClick">
        <el-tab-pane
            v-for="workflow in workflowList"
            :label="workflow.workflowName"
            :key="workflow.id"
            :name="workflow.id"
        >
          <el-tabs type="border-card" @tab-click="handleProcessClick">
            <el-tab-pane
                v-for="process in workflow.processes"
                :label="process.processName"
                :key="process.id"
                :name="process.id + ''"
            >
              <!--              工具栏-->
              <el-row>
                <el-button type="primary" @click="addOrUpdate">添加任务</el-button>
                <el-button type="danger" :disabled="selectedTasks.length === 0" @click="batchDeleteTasks">批量删除
                </el-button>
              </el-row>
              <!--              任务列表-->
              <el-card>
                <el-table
                    :data="taskList"
                    border
                    stripe
                    @selection-change="selectTaskChange"
                >
                  <el-table-column type="selection"/>
                  <el-table-column prop="taskCode" label="任务编号" fixed="left"/>
                  <el-table-column prop="taskName" label="任务名称"/>
                  <el-table-column prop="workstationCode" label="工作站编号"/>
                  <el-table-column prop="scheduleQuantity" label="排产数量"/>
                  <el-table-column prop="producedQuantity" label="已生产数量"/>
                  <el-table-column prop="startProductionTime" label="开始生产时间"/>
                  <el-table-column prop="productionDuration" label="预计生产时长"/>
                  <el-table-column prop="estimatedCompletionTime" label="预计完成时间"/>
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                      <el-button size="small" @click="updateTaskView(scope.row)">编辑</el-button>
                      <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>

                </el-table>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeProSchedule">关闭</el-button>
      </span>
    </template>
  </el-dialog>
  <!--  添加/编辑任务弹窗-->
  <el-dialog
      :title="addOrUpdateDialogTitle"
      v-model="addOrUpdatedialogView"
      width="80%"
  >
    <el-form v-model="taskForm">
      <el-form-item label="任务编码">
        <el-row style="width: 100%;">
          <el-col :span="22">
            <el-input v-model="taskForm.taskCode" placeholder="输入任务编码"/>
          </el-col>
          <el-col :span="2">
            <el-switch :disabled="isDetail" @click="autoCode" inline-prompt active-text="自动生成"
                       inactive-text="自动生成" v-model="isAutoCode"/>
          </el-col>
        </el-row>

      </el-form-item>
      <el-form-item label="任务名称">
        <el-input v-model="taskForm.taskName" placeholder="输入任务名称"/>
      </el-form-item>
      <el-form-item label="工作站编码">
        <el-input v-model="taskForm.workstationCode" disabled>
          <template #append>
            <el-button @click="selectWorkstation">
              <el-icon>
                <Search/>
              </el-icon>
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="排产数量">
        <el-input-number v-model="taskForm.scheduleQuantity" :min="1"/>
      </el-form-item>
      <el-form-item label="开始生产时间">
        <el-date-picker
            v-model="taskForm.startProductionTime"
            type="datetime"
            placeholder="选择开始生产时间"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
        <el-form-item label="生产时长">
          <el-input-number v-model="taskForm.productionDuration" :min="1"/>
        </el-form-item>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeAddorUpdateDialog">关闭</el-button>
      </span>
      <span class="dialog-footer">
        <el-button @click="handleAddTask" type="success">确认</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog title="选择工作站" v-model="selectWorkstationView" width="80%">
    <workstation-list @select-workstation="handleSelectedWorkstation"/>
  </el-dialog>
</template>

<script setup>
// 导入必须的内容
import {ref, onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {getCodeAuto} from "@/api/codeAuto.js"
import {getProScheduleList, getMaterialWorkflowList} from "@/api/proschedule.js"
import {
  getProductionOrderList,
  queryById,
  getProductionOrderToSchedule,
  queryByCode,
  addProductionOrder,
  deleteProductionOrder,
  updateProductionOrder,
  batchDeleteProductionOrder
} from "@/api/production-order.js";
import {getWorkstationByCode} from "@/api/workstation.js"
import {addTask, queryTask, queryTaskByCode, updateTask, deleteTask, batchDeleteTask} from "@/api/task.js"
// 导入字典相关的API
import Bom from "@/views/pro/production-order/Bom.vue";
import {getDictDataList, getDictDataById} from "@/api/dictData.js";
import ProductList from "@/views/pro/workflow/product-list.vue";
import SupplierList from "@/views/pro/production-order/supplier-list.vue";
import CustomerList from "@/views/pro/production-order/customer-list.vue";
import {getMaterialByCode} from "@/api/material.js";
import {getSupplierByCode} from "@/api/supplier.js";
import {getCustomerByCode} from "@/api/customer.js"
import {Search} from "@element-plus/icons-vue";
import WorkflowProduct from "@/views/pro/workflow/workflow-product.vue";
import WorkflowProcess from "@/views/pro/workflow/workflow-process.vue";
import WorkstationList from "@/views/pro/proschedule/workstation-list.vue";


// ----- 属性声明 ↓
//编码自动生成switch控制
const isAutoCode = ref(false)
//选择工作站弹窗控制
const selectWorkstationView = ref(false)
//添加任务弹窗
const addOrUpdateDialogTitle = ref("添加任务")
//添加/编辑弹窗控制
const addOrUpdatedialogView = ref(false)
//当前的工单id
const currentProductionOrderId = ref("")
//当前的工艺id
const currentWorkflowId = ref("")
//当前的工序id
const currentProcessId = ref("")
//任务表单
const taskForm = ref({
  taskId: "",
  processId: "",
  workflowId: "",
  productionOrderId: "",
  taskCode: "",
  taskName: "",
  workstationCode: "",
  scheduleQuantity: "",
  startProductionTime: "",
  productionDuration: "",
  workstation: {}
})
//工艺列表
const workflowList = ref([])
//任务列表
const taskList = ref([])
//工艺列表是否为空
const isNullWithWorkflow = ref(true)
// 绑定搜索表单的数据
const searchForm = ref({
  productionOrderCode: "",
  productionOrderName: "",
  materialCode: "",
  materialName: "",
  requestDate: "",
  productionOrderSource: "",
  customerCode: "",
  customerName: "",

})
// 工单列表数据
const productionOrderList = ref([])
// 分页相关数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
//
const dialogTitle = ref("查看工单")
// 新增/编辑表单的数据绑定对象
const productionOrderForm = ref({
  id: "",
  productionOrderCode: "",
  productionOrderName: "",
  productionOrderSource: "",
  productionOrderType: "",
  productionOrderStatus: "",
  orderCode: "",
  materialCode: "",
  customerCode: "",
  supplierCode: "",
  productionOrderQuantity: 0,
  requestDate: "",
  qrCodeUrl: "",
  material: {name: "", specification: "", unit: {}, id: ""},
  supplier: {name: ""},
  customer: {name: ""},
  sourceDictData: {},

})

//工单来源列表
const productionOrderSourceDictDataList = ref([]);
//编辑标识
const isEdit = ref(false)
//查看工单详情
const isDetail = ref(false)
//弹窗控制
const scheduleDialogVisable = ref(false)
//选中的任务
const selectedTasks = ref([])
// ----- 属性声明 ↑
// -- 函数声明 ↓
//生成编码
const autoCode = () => {
  if (isAutoCode.value) {
    getCodeAuto("TASK_CODE").then(res => {
      if (res.code === 200) {
        taskForm.value.taskCode = res.data
      } else {
        isAutoCode.value = false
        ElMessage.error("编码生成失败")
      }
    })
  } else {
    taskForm.value.taskCode = ""
  }
}
//删除事件
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除任务 "${row.taskName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    deleteTask(row.taskId).then(res => {
      if (res.code === 200) {
        queryTaskList()
        ElMessage.success(res.msg)
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })

}

//批量删除事件
const batchDeleteTasks = () => {
  ElMessageBox.confirm(
      `确定要删除任务 "${row.taskName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    let params = ""
    selectedTasks.value.forEach(item => {
      params += "id=" + item.taskId + "&"
    })
    params = params.substring(0, params.length - 1)
    batchDeleteTask(params).then(res => {
      if (res.code === 200) {
        queryTaskList()
        ElMessage.success(res.msg)
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })


}
//添加按钮事件
const addOrUpdate = () => {
  addOrUpdateDialogTitle.value = "添加任务"
  addOrUpdatedialogView.value = true
}
//编辑按钮事件
const updateTaskView = (row) => {
  isEdit.value = true
  queryTaskByCode(row.taskCode).then(res => {
    taskForm.value = res.data
  })
  addOrUpdatedialogView.value = true
  addOrUpdateDialogTitle.value = "编辑任务"

}
//查询任务列表
const queryTaskList = () => {
  //根据工单id，工艺id，工序id查询
  taskForm.value.processId = currentProcessId.value
  taskForm.value.productionOrderId = currentProductionOrderId.value
  taskForm.value.workflowId = currentWorkflowId.value
  queryTask(taskForm.value).then(res => {
    taskList.value = res.data
  })
}
//当前工艺id
const handleWorkflowClick = (panel) => {
  taskForm.value.workflowId = panel.props.name
  currentWorkflowId.value = panel.props.name
  console.log(panel.props.name)
}
//处理添加/编辑数据
const handleAddTask = () => {
  if (isEdit.value) {
    updateTask(taskForm.value).then(res => {
      if (res.code === 200) {
        queryTaskList();
        ElMessage.success(res.msg)
      } else {
        ElMessage.error(res.msg)
      }
    })
  } else {
    addTask(taskForm.value).then(res => {
      if (res.code === 200) {
        queryTaskList();
        ElMessage.success(res.msg)
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  closeAddorUpdateDialog();
}
//获取当前工序
const handleProcessClick = (panel) => {
  taskForm.value.processId = panel.props.name
  currentProcessId.value = panel.props.name
  console.log(panel.props.name)
  queryTaskList();
}
//获取工作站编码
const handleSelectedWorkstation = (workstationCode) => {
  getWorkstationByCode(workstationCode).then(res => {
    taskForm.value.workstationCode = workstationCode
    taskForm.value.workstation = res.data
    selectWorkstationView.value = false;
  })
}
//关闭按钮事件
const closeAddorUpdateDialog = () => {
  taskForm.value = {
    taskCode: "",
    taskName: "",
    workstationCode: "",
    scheduleQuantity: "",
    startProductionTime: "",
    productionDuration: "",
  }
  addOrUpdatedialogView.value = false
  isEdit.value = false;
  queryTaskList()
}
//点击选择工作站按钮事件
const selectWorkstation = () => {
  selectWorkstationView.value = true;
}
//多选按钮
const selectTaskChange = (selection) => {
  selectedTasks.value = selection
  console.log(selectedTasks.value)
}
//排产按钮
const handleProSchedule = (row) => {
  queryById(row.id).then(res => {
    productionOrderForm.value = res.data
  })
  taskForm.value.productionOrderId = row.id
  currentProductionOrderId.value = row.id
  console.log("productionOrderId")
  console.log(taskForm.value.productionOrderId)
  //加载工艺列表数据
  getMaterialWorkflowList(row.materialCode).then(res => {
    workflowList.value = res.data
    if (workflowList.value === []) {
      isNullWithWorkflow.value = true;
    } else {
      isNullWithWorkflow.value = false;
    }
  })
  dialogTitle.value = "工单排产"
  scheduleDialogVisable.value = true;
}
// 查看工单
const previewProductionOrder = (row) => {
  dialogTitle.value = "查看工单"
  queryById(row.id).then(res => {
    productionOrderForm.value = res.data
    changeSource(res.data.productionOrderSource);
    isDetail.value = true;
    scheduleDialogVisable.value = true;
  })
}


//重置查询表单
const resetSearch = () => {
  searchForm.value.productionOrderCode = "";
  searchForm.value.productionOrderName = "";
  searchForm.value.productionOrderSource = "";
  searchForm.value.productionOrderType = "";
  searchForm.value.customerName = "";
  searchForm.value.customerCode = "";
  searchForm.value.materialCode = "";
  searchForm.value.materialName = "";
  searchForm.value.requestDate = "";
}
//加载工单来源字典的函数
const loadProductionOrderSourceDictDataList = () => {
  getDictDataList({dictType: "PRODUCTION_ORDER_SOURCE"}).then(res => {
    productionOrderSourceDictDataList.value = res.data.records;
  })
}


// 改变了每页大小的事件
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize;
  handleSearch();
}
// 改变页面的事件  翻页事件
const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;
  handleSearch();
}
// 搜索数据的事件
const handleSearch = () => {
  // 调用查询的接口查询数据
  let params = {};// 这里需要组织参数--------------
  // 请求参数就是searchForm.vaue 和  page相关的参数
  params = searchForm.value;// 这里只包含了搜索条件，没有分页参数
  params.pageNum = pagination.value.currentPage;
  params.pageSize = pagination.value.pageSize;
  getProScheduleList(params).then(res => {
    productionOrderList.value = res.data.list;
    pagination.value.total = res.data.total;
    console.log("productionOrderList:")
    console.log(productionOrderList.value)
  })

}
//关闭按钮
const closeProSchedule = () => {
  productionOrderForm.value = {
    id: "",
    productionOrderCode: "",
    productionOrderName: "",
    productionOrderSource: "",
    productionOrderType: "",
    productionOrderStatus: "",
    orderCode: "",
    materialCode: "",
    customerCode: "",
    supplierCode: "",
    productionOrderQuantity: 0,
    requestDate: "",
    qrCodeUrl: "",
    material: {name: "", specification: "", unit: {}, id: ""},
    supplier: {name: ""},
    customer: {name: ""},
    sourceDictData: {},
  }
  scheduleDialogVisable.value = false;
}
// -- 函数声明 ↑
onMounted(() => {
  handleSearch();
  loadProductionOrderSourceDictDataList()
})


</script>

<style scoped>

</style>